package com.wly.network 
{
	import com.wly.network.packet.SCPacketPool;
	import com.wly.network.packet.CSPacket;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.utils.ByteArray;
	import flash.net.Socket;
	
	/**
	 * @author Administrator
	 */
	public class Connector 
	{
		private var _socket:Socket;
		private var _byteArr:ByteArray;
		
		public function connectto(ipAddr:String, port:int):void
		{
			_socket = new Socket();
			_socket.addEventListener(ProgressEvent.SOCKET_DATA, onGetData);
			_socket.addEventListener(IOErrorEvent.IO_ERROR, onSocketError);
			_socket.addEventListener(Event.CLOSE, onSocketClose);
			_socket.connect(ipAddr, port);
		}
		
		public function sendPkg(pkt:CSPacket):void
		{
			if(!pkt || !_socket)
			{
				return;
			}
			
			_socket.writeBytes(pkt.serialization());
		}
		
		public function disConnect():void
		{
			if(_socket)
			{
				_socket.close();
				_socket.removeEventListener(ProgressEvent.SOCKET_DATA, onGetData);
				_socket.removeEventListener(IOErrorEvent.IO_ERROR, onSocketError);
				_socket = null;
			}
		}
		
		private function onGetData(e:ProgressEvent):void
		{
			var byteArr:ByteArray = new ByteArray();
			_socket.readBytes(byteArr);
			SCPacketPool.getInstance().onGetData(byteArr);	
		}
		
		private function onSocketError(e:IOErrorEvent):void
		{
			trace(this, e.text);
		}
		
		public function onSocketClose(e:Event):void
		{
			trace(this, "socket close");
		}
	}
}
